package kr.aow.web.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import kr.aow.member.service.IMemberService;
import kr.aow.member.service.IMemberService.MemberResult;
import kr.aow.vo.MemberDTO;
import kr.aow.web.vlidator.Insert;
import kr.aow.web.vlidator.Update;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/member/*")
public class MemberController {

	@Inject
	private IMemberService service;
	
	public IMemberService getService() {
		return service;
	}

	public void setService(IMemberService service) {
		this.service = service;
	}

	@RequestMapping("memberList.do")
	public String memberList(Model model){
		List<MemberDTO> memberList = service.getMemberList();
		model.addAttribute("memberList", memberList);
		String viewName = "member/memberList";
		return viewName;
	}
	
	
	@RequestMapping("memberView.do")
	public String memberView(@RequestParam(value="mem_id") String mem_id
			, Model model, HttpServletResponse response) throws IOException{
//		String mem_id = request.getParameter("mem_id");
		if(StringUtils.isBlank(mem_id)){
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, 
					"조회하고 싶은 회원이 누구지??");
			return null;
		}
		MemberDTO member = service.getMember(mem_id);
		model.addAttribute("member", member);
		String viewName = "member/memberView";
		return viewName;
	}
	
	@Inject
	LocalValidatorFactoryBean validator;
	
	@RequestMapping(value="memberUpdate.do", method=RequestMethod.GET)
	public ModelAndView memberUpdate(@ModelAttribute("member") MemberDTO member,
			BindingResult error,
			ModelMap model, HttpServletResponse response
			) throws IOException{
		validator.validate(member, error, Update.class);
		String viewName = null;
			
		if(error.hasErrors()){
			viewName = "member/memberView";
		}else{
			
		
		
			MemberResult result = service.modifyMember(member);
			String msg = "";
			
			if(result == MemberResult.OK){
				msg = URLEncoder.encode("수정이 정상 처리 됐음", "UTF-8");
				viewName = "redirect:/member/memberView.do?mem_id="
							+member.getMb_id()+"&msg="+msg;
				
			}else if(result == MemberResult.Failed){
				msg = "알수없는 이유로 수정에 실패ㅠ.ㅠ.ㅠ 쫌 있다 다시 해봐요.";
				model.addAttribute("msg", msg);
				viewName="member/memberView";
				
			}else if(result == MemberResult.NOTEXIST){
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, "정상적인 루트를 타지 않았네요.");
				return null;
			}else if(result == MemberResult.INVALIDPASSWORD){
				msg = "비밀번호 오류";
				model.addAttribute("msg", msg);
				viewName ="member/memberView";
			}
		}
		ModelAndView mav = new ModelAndView();
		mav.addAllObjects(model);
		mav.setViewName(viewName);
		return mav;
	}
	@RequestMapping("memberForm.do")
	public String memberForm(){
		return "member/memberForm";
	}
	
	// JSR-303 검증
//	1. BindingResult 나 Errors를 검증 대상 객체 다음에 파라미터로 선언.
//	2. @Valid 어노테이션을 검증대상 객체에 선언
//	3. 검증 규칙 적용.
//	4. Errors 에  에러정보가 있는지 확인 후 뷰로 포워딩.
	@RequestMapping("memberInsert.do")
	public String memberInsert(@ModelAttribute("member") MemberDTO member,
			Errors error,
			Model model) throws UnsupportedEncodingException{
		
		validator.validate(member, error, Insert.class);
		
		if(error.hasErrors()){
			return "member/memberForm";
		}
			
		MemberResult result = service.createMember(member);
		String msg = null;
		String viewName = null;
		if(result == MemberResult.OK){
			msg = URLEncoder.encode("정상적으로 가입이 완료되었음.", "UTF-8");
			viewName = "redirect:/index.jsp?msg="+msg;
		}else if(result == MemberResult.PKDuplicated){
			msg = "아이디가 중복되었습니다. 다른거 쓰시지!!";
			model.addAttribute("msg", msg);
			viewName = "member/memberForm";
		}else {
			msg = "서버측 오류 발생!! 잠시뒤 다시 등록해주셈";
			model.addAttribute("msg", msg);
			viewName = "member/memberForm";
		}
		return viewName;
	}
}
